package com.jt.auth.service;

import com.jt.auth.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private RemoteUserService remoteUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //假数据：
        /*//1.基于用户名查询用户信息(用户名,用户状态,密码,....)
        //Userinfo userinfo=userMapper.selectUserByUsername(username);
        String encodedPassword=passwordEncoder.encode("123456");
        //2.查询用户权限信息(后面会访问数据库)
        //这里先给几个假数据
        List<GrantedAuthority> authorities =
                AuthorityUtils.createAuthorityList(//这里的权限信息先这么写,后面讲
                        "sys:res:create", "sys:res:retrieve");
        //3.对用户信息进行封装
        return new User(username,encodedPassword,authorities);*/

        //数据库数据：
        User user=
        remoteUserService.SelectUserByUsername(username);
        if (user==null)
            throw new UsernameNotFoundException("用户名不存在");
        List<String> permissions =
                remoteUserService.selectUserPermissions(user.getId());

        return new  org.springframework.security.core.userdetails.User(
                username,user.getPassword(),
                AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));

    }

}
